﻿using System;
using System.Data;
using BO.Infrastructure.StaticData;
using BO.Infrastructure.Utils;
using BO.News;
using ChannelVN.Cached;
using GUI.Extensions;

namespace GUI.Controls.Sport
{
    public partial class BoxNews : System.Web.UI.UserControl
    {
        public int ZoneId { get; set; }
        public bool GetDataFromNoCacheLayer = false;
        private const string LiFormat = "<li>{3}<p><a href=\"{0}\" title=\"{2}\">{1}</a></p></li>";

        private const int ImageHeight = 75;
        private const int ImageWidth = 100;
        private const int Top = 4;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (RequestExtensions.CatUrl.Equals("hau-truong-the-thao", StringComparison.InvariantCultureIgnoreCase))
            {
                Visible = false;
                return;
            }

            var enableHtmlCaching = CacheSettingExtensions.EnableCacheHtml && GetDataFromNoCacheLayer;
            var bo = enableHtmlCaching
                    ? NewsBO_NoCache.GetInstance()
                    : NewsBO.GetInstance();
            var isCachedUpdating = enableHtmlCaching && CacheController.IsCachedUpdating;

            var dt = bo.GetSportNewsByPosition(
                top: Top,
                typeId: DefinedConstants.SportNews.TypeIds.SlideTrangChu,
                zoneId: ZoneId,
                getDataFromMasterDataBase: isCachedUpdating);
            Visible = DataBind(dt);

            if (!Visible) return;
            var objCat = NewsBO.GetInstance().GetCategoryDetail(ZoneId);
            if (objCat != null)
            {
                ltrZoneName.Text = string.Format("<a title=\"{1}\" href=\"{0}\">{1}</a>", objCat.Url, objCat.Name);
            }
        }

        public bool DataBind(DataTable dt)
        {
            if (dt != null && dt.Rows.Count > 0)
            {
                var sb = new System.Text.StringBuilder();

                foreach (DataRow r in dt.Rows)
                {
                    var avatar = PresentationUtils.Photo.BuildNewsAvatar(r, ImageWidth, ImageHeight, lazyLoad: true);

                    sb.Append(string.Format(
                            LiFormat,
                            r[SqlConstants.NewsPublish.Url],
                            r[SqlConstants.NewsPublish.Title],
                            PresentationUtils.EnCode(r[SqlConstants.NewsPublish.Title].ToString()),
                            avatar
                        ));
                }
                ltrList.Text = sb.ToString();
                return true;
            }
            return false;
        }
    }
}